<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="原理搞清楚了，那么下面我们就先编写一个独立按键的程序，把最基本的功能验证一下。 123456789101112131415161718192021222324252627282930#include &amp;lt;reg52.h&amp;gt;sbit ADDR0 = P1^0;sbit ADDR1 = P1^1;sbit ADDR2 = P1^2;sbit ADDR3 = P1^3;sbit ENLED =">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="8.5、独立按键扫描程序">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu052/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="原理搞清楚了，那么下面我们就先编写一个独立按键的程序，把最基本的功能验证一下。 123456789101112131415161718192021222324252627282930#include &amp;lt;reg52.h&amp;gt;sbit ADDR0 = P1^0;sbit ADDR1 = P1^1;sbit ADDR2 = P1^2;sbit ADDR3 = P1^3;sbit ENLED =">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-27T03:34:13.020Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="8.5、独立按键扫描程序">
<meta name="twitter:description" content="原理搞清楚了，那么下面我们就先编写一个独立按键的程序，把最基本的功能验证一下。 123456789101112131415161718192021222324252627282930#include &amp;lt;reg52.h&amp;gt;sbit ADDR0 = P1^0;sbit ADDR1 = P1^1;sbit ADDR2 = P1^2;sbit ADDR3 = P1^3;sbit ENLED =">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu052/">





  <title>8.5、独立按键扫描程序 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu052/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">8.5、独立按键扫描程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:36:35+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>原理搞清楚了，那么下面我们就先编写一个独立按键的程序，把最基本的功能验证一下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit ADDR0 = P1^0;</span><br><span class="line">sbit ADDR1 = P1^1;</span><br><span class="line">sbit ADDR2 = P1^2;</span><br><span class="line">sbit ADDR3 = P1^3;</span><br><span class="line">sbit ENLED = P1^4;</span><br><span class="line">sbit LED9 = P0^7;</span><br><span class="line">sbit LED8 = P0^6;</span><br><span class="line">sbit LED7 = P0^5;</span><br><span class="line">sbit LED6 = P0^4;</span><br><span class="line">sbit KEY1 = P2^4;</span><br><span class="line">sbit KEY2 = P2^5;</span><br><span class="line">sbit KEY3 = P2^6;</span><br><span class="line">sbit KEY4 = P2^7;</span><br><span class="line">void main()&#123;</span><br><span class="line">    ENLED = 0;  //选择独立 LED 进行显示</span><br><span class="line">    ADDR3 = 1;</span><br><span class="line">    ADDR2 = 1;</span><br><span class="line">    ADDR1 = 1;</span><br><span class="line">    ADDR0 = 0;</span><br><span class="line">    P2 = 0xF7;  //P2.3 置 0，即 KeyOut1 输出低电平</span><br><span class="line">   </span><br><span class="line">    while (1)&#123;</span><br><span class="line">        //将按键扫描引脚的值传递到 LED 上</span><br><span class="line">        LED9 = KEY1;  //按下时为 0，对应的 LED 点亮</span><br><span class="line">        LED8 = KEY2;</span><br><span class="line">        LED7 = KEY3;</span><br><span class="line">        LED6 = KEY4;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>本程序固定在 KeyOut1 上输出低电平，而 KeyOut2～4 保持高电平，就相当于是把矩阵按键的第一行，即 K1～K4 作为 4 个独立按键来处理，然后把这 4 个按键的状态直接送给LED9～6 这 4 个 LED 小灯，那么当按键按下时，对应按键的输入引脚是 0，对应小灯控制信号也是 0，于是灯就亮了，这说明上述关于按键检测的理论都是可实现的。</p>
<p>绝大多数情况下，按键是不会一直按住的，所以我们通常检测按键的动作并不是检测一个固定的电平值，而是检测电平值的变化，即按键在按下和弹起这两种状态之间的变化，只要发生了这种变化就说明现在按键产生动作了。</p>
<p>程序上，我们可以把每次扫描到的按键状态都保存起来，当一次按键状态扫描进来的时候，与前一次的状态做比较，如果发现这两次按键状态不一致，就说明按键产生动作了。当上一次的状态是未按下而现在是按下，此时按键的动作就是“按下”；当上一次的状态是按下而现在是未按下，此时按键的动作就是“弹起”。显然，每次按键动作都会包含一次“按下”和一次“弹起”，我们可以任选其一来执行程序，或者两个都用，以执行不同的程序也是可以的。下面就用程序来实现这个功能，程序只取按键 K4 为例。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit ADDR0 = P1^0;</span><br><span class="line">sbit ADDR1 = P1^1;</span><br><span class="line">sbit ADDR2 = P1^2;</span><br><span class="line">sbit ADDR3 = P1^3;</span><br><span class="line">sbit ENLED = P1^4;</span><br><span class="line">sbit KEY1 = P2^4;</span><br><span class="line">sbit KEY2 = P2^5;</span><br><span class="line">sbit KEY3 = P2^6;</span><br><span class="line">sbit KEY4 = P2^7;</span><br><span class="line">unsigned char code LedChar[] = &#123;  //数码管显示字符转换表</span><br><span class="line">    0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,</span><br><span class="line">    0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E</span><br><span class="line">&#125;;</span><br><span class="line">void main()&#123;</span><br><span class="line">    bit backup = 1;  //定义一个位变量，保存前一次扫描的按键值</span><br><span class="line">    unsigned char cnt = 0;  //定义一个计数变量，记录按键按下的次数</span><br><span class="line">    ENLED = 0;  //选择数码管 DS1 进行显示</span><br><span class="line">    ADDR3 = 1;</span><br><span class="line">    ADDR2 = 0;</span><br><span class="line">    ADDR1 = 0;</span><br><span class="line">    ADDR0 = 0;</span><br><span class="line">    P2 = 0xF7;  //P2.3 置 0，即 KeyOut1 输出低电平</span><br><span class="line">    P0 = LedChar[cnt];  //显示按键次数初值</span><br><span class="line">    while (1)&#123;</span><br><span class="line">        //当前值与前次值不相等说明此时按键有动作</span><br><span class="line">        if (KEY4 != backup)&#123;</span><br><span class="line">            //如果前次值为 0，则说明当前是由 0 变 1，即按键弹起</span><br><span class="line">            if (backup == 0)&#123;</span><br><span class="line">                cnt++;  //按键次数+1</span><br><span class="line">                //只用 1 个数码管显示，所以加到 10 就清零重新开始</span><br><span class="line">                if (cnt &gt;= 10)&#123;</span><br><span class="line">                   cnt = 0;</span><br><span class="line">                &#125;</span><br><span class="line">                P0 = LedChar[cnt]; //计数值显示到数码管上</span><br><span class="line">            &#125;</span><br><span class="line">            backup = KEY4;  //更新备份为当前值，以备进行下次比较</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>先来介绍出现在程序中的一个新知识点，就是变量类型——bit，这个在标准 C 语言里边是没有的。51 单片机有一种特殊的变量类型就是 bit 型。比如 unsigned char 型是定义了一个无符号的 8 位的数据，它占用一个字节(Byte)的内存，而 bit 型是 1 位数据，只占用 1 个位(bit)的内存，用法和标准 C 中其他的基本数据类型是一致的。它的优点就是节省内存空间，8 个bit 型变量才相当于 1 个 char 型变量所占用的空间。虽然它只有 0 和 1 两个值，但也已经可以表示很多东西了，比如：按键的按下和弹起、LED 灯的亮和灭、三极管的导通与关断等等，联想一下已经学过的内容，它是不是能用最小的内存代价来完成很多工作呢？</p>
<p>在这个程序中，我们以 K4 为例，按一次按键，就会产生“按下”和“弹起”两个动态的动作，我们选择在“弹起”时对数码管进行加 1 操作。理论是如此，大家可以在板子上用K4 按键做做实验试试，多按几次，是不是会发生这样一种现象：有的时候我明明只按了一下按键，但数字却加了不止 1，而是 2 或者更多？但是我们的程序并没有任何逻辑上的错误，这是怎么回事呢？于是我们就得来说说按键抖动和消抖的问题了。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu051/" rel="next" title="8.4、单片机按键介绍">
                <i class="fa fa-chevron-left"></i> 8.4、单片机按键介绍
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2014/12/01/mcu053/" rel="prev" title="8.6、单片机按键消抖程序">
                8.6、单片机按键消抖程序 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
